package com.lagou.dubbo.service;

import com.lagou.dubbo.common.MonitorHelper;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class TPService {

    @Reference(check = false, filter = "TPMonitorFilter")
    private DubboSleepService dubboSleepService;

    /**
     * 测试TP性能
     */
    public void testTP() throws InterruptedException {

        // 开启测试状态
        MonitorHelper.TESTING = true;

        long startTime = System.currentTimeMillis();
        // 调用次数
        long times = 0;

        while (true) {
            long currentTime = System.currentTimeMillis();
            if (currentTime - startTime >= MonitorHelper.TEST_TIME) {
                // 满足测试时间后退出，避免长时间占用cpu，造成死机
                break;
            }

            // 开始调用测试接口
            MonitorHelper.execute(new Runnable() {
                @Override
                public void run() {
                    dubboSleepService.methodA();
                }
            });

            MonitorHelper.execute(new Runnable() {
                @Override
                public void run() {
                    dubboSleepService.methodB();
                }
            });

            MonitorHelper.execute(new Runnable() {
                @Override
                public void run() {
                    dubboSleepService.methodC();
                }
            });

            // 统计调用次数
            times += 3;
            Thread.sleep(MonitorHelper.PAUSE_TIME);
        }

        // 关闭测试状态
        MonitorHelper.TESTING = false;
        System.out.println();
        System.out.println("调用接口次数：" + times);

        // 等待调用完成后清除tp信息
        Thread.sleep(500);
        cleanTP();
    }

    /**
     * 打印TP监控记录
     */
    @Async
    public void printTP() {
        if (MonitorHelper.TESTING && MonitorHelper.tpMap.size() > 0) {
            MonitorHelper.printTP();
        }
    }

    /**
     * 清除TP监控记录
     */
    private void cleanTP() {
        MonitorHelper.cleanTP();
    }
}
